package com.room.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyh.dao.dto.RoomDto;
import com.cyh.dao.dto.SeatDto;
import com.cyh.dao.entity.Report;
import com.cyh.dao.entity.Reserve;
import com.cyh.dao.entity.Room;
import com.cyh.dao.entity.SysUser;
import com.cyh.dao.mapper.ReportMapper;
import com.cyh.dao.mapper.RoomMapper;
import com.room.core.dto.UserInfo;
import com.room.core.util.R;
import com.room.dto.WxSubscribeDto;
import com.room.vo.ReserveVo;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;

@Component
public class RoomService extends ServiceImpl<RoomMapper, Room> {
    @Autowired
    private ReserveService reserveService;

    @Autowired
    private ReportService reportService;

    public List<RoomDto> roomListByBuildId(Long buildId, Integer dmtIs) {
        return baseMapper.getRoomList(buildId, dmtIs);
    }

    public List<Map<String, Object>> seatListByRoomId(Long roomId) {
        List<SeatDto> seatList = baseMapper.getSeatList(roomId);

        List<Map<String, Object>> parList = new ArrayList<>();
        int index = 0;
        for (int i = 0; i < seatList.size(); i+=6) {
            List<Map<String, Object>> tmpList = new ArrayList<>();
            for (int j = 0; j < 6 && i + j < seatList.size(); j++) {

                Map<String, Object> map = new HashMap<>();
                map.put("obj", seatList.get(i + j));
                map.put("top", j / 3 * 27);
                map.put("left", j % 3 * 31);
                tmpList.add(map);
            }

            if(tmpList.size() != 0){
                Map<String, Object> map = new HashMap<>();
                map.put("obj", tmpList);
                map.put("top", index  / 3 * 80);
                map.put("left", index  % 3 * 110);
                parList.add(map);
            }
            index++;
        }
        return parList;
    }


    public R reserve(UserInfo userInfo, ReserveVo reserveVo) {

        int count = reserveService.count(new QueryWrapper<Reserve>()
                .eq("seat_id", reserveVo.getSeatId())
                .eq("time_interval", reserveVo.getTimeInterval())
                .eq("invalid_is", 0));
        if (count == 0) {

            int count1 = reserveService.count(new QueryWrapper<Reserve>()
                    .eq("user_id", userInfo.getId())
                    .eq("invalid_is", 0));
            if (count1 > 0) {
                return R.fail("只能预约一个座位！！！");
            }
            Reserve reserve = new Reserve();
            reserve.setTimeInterval(reserveVo.getTimeInterval());
            reserve.setInvalidIs(0);
            reserve.setSeatId(reserveVo.getSeatId());
            reserve.setUserId(userInfo.getId());
            reserveService.save(reserve);
            return R.success();
        } else {
            //失败
            return R.fail("该座位已经被预约！！！");
        }
    }

    public R autoReserve(UserInfo userInfo, ReserveVo reserveVo) {
        int count1 = reserveService.count(new QueryWrapper<Reserve>()
                .eq("user_id", userInfo.getId())
                .eq("invalid_is", 0));
        if (count1 > 0) {
            return R.fail("只能预约一个座位！！！");
        }
        Room room = baseMapper.autoReserveSeatList(reserveVo.getRoomId(), reserveVo.getTimeInterval());
        if (room == null) {
            return R.fail("没有座位可以预约");
        } else {
//            reserveVo.set
            reserveVo.setSeatId(room.getId());
            R reserve = reserve(userInfo, reserveVo);
            if (reserve.isSuccess()) {
                return R.success("已经为您预约到座位：" + room.getName());
            } else {
                return reserve;
            }
        }
    }

    @Autowired
    private ReportMapper reportMapper;

    public R report(UserInfo userInfo, String originalFilename, Integer seatId, Integer timeInterval) {

        Integer integer = reportMapper.selectCount(new LambdaQueryWrapper<Report>()
                .eq(Report::getSeatId, seatId)
                .eq(Report::getTimeInterval, 0)
                .eq(Report::getUserId, userInfo.getId()));
        if (integer > 0) {
            return R.fail("您已经举报过了，不能重复举报");
        }
        List<Reserve> list = reserveService.list(new LambdaQueryWrapper<Reserve>()
                .eq(Reserve::getSeatId, seatId)
                .eq(Reserve::getTimeInterval, timeInterval)
                .eq(Reserve::getInvalidIs, 0)
        );

        if (!CollectionUtils.isEmpty(list)) {
            Reserve reserve = list.get(0);
            Report report = new Report();
            report.setImgUrl(originalFilename);
            report.setReportUserId(reserve.getUserId());
            report.setSeatId(reserve.getSeatId());
            report.setTimeInterval(timeInterval);
            report.setUserId(userInfo.getId());
            reportMapper.insert(report);
            send(reserve.getUserId());
            return R.success("举报成功");
        } else {
            return R.fail("该座位没有人预约");
        }

    }


    @Autowired
    private WxMaService wxService;
    @Autowired
    private SysUserService sysUserService;

    public void send(Long userId) {
        try {
            SysUser user = sysUserService.getById(userId);
            String accessToken = wxService.getAccessToken();
            Map<String, Object> data = new HashMap<>();
            Map<String, String> value = new HashMap<>();
            value.put("value", "发现您已经离开了座位，请尽快回到座位");
            data.put("thing1", value);

            value = new HashMap<>();
            value.put("value", "半个小时内未到位置，进行占座记录");
            data.put("thing3", value);
            WxSubscribeDto subscribeDto = WxSubscribeDto.builder()
                    .access_token(accessToken)
                    .touser(user.getWeixinOpenid())
                    .template_id("ggVUb3Cb76E77EVf4eGxCc-JYnwTP8ilkqLCuh2I7JE")
                    .data(data).build();
            String s = JSON.toJSONString(subscribeDto);
            String responseContent = wxService.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send",
                    s);
        } catch (WxErrorException e) {

        }
    }

    public R reportBack(UserInfo userInfo, String originalFilename) {
        List<Report> list = reportService.list(new LambdaQueryWrapper<Report>()
                .eq(Report::getReportUserId, userInfo.getId())
                .eq(Report::getReportUserBack, 0));
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(list)) {
            LocalDateTime now = LocalDateTime.now();
            for (Report report : list) {
                Duration duration = Duration.between(report.getReportTime(), now);
                if (duration.toMinutes() >= 30) {
                    report.setReportUserBack(2);
                } else {
                    report.setReportUserBack(1);
                }
                report.setReportUserImg(originalFilename);
            }
            reportService.updateBatchById(list);
        }
        return R.success();
    }
}
